// sysenv.cpp
#include "SysEnv.h"
#include <QStandardPaths>
#include <QDir>
#include <QFileInfo>
#include <QCoreApplication>
#include <DatabaseManager/DatabaseManager.h>

SysEnv& SysEnv::instance()
{
    static SysEnv env;
    return env;
}

void SysEnv::setConfigInAppDir(const QString &relativePath)
{
    QString configDir = QCoreApplication::applicationDirPath();
    QString fullPath = configDir + "/" + relativePath;

    QFileInfo fileInfo(fullPath);
    QDir dir = fileInfo.dir();
    if (!dir.exists()) {
        dir.mkpath(".");
    }

    setIniPath(fullPath);
}

void SysEnv::setIniPath(const QString &absoluteFilePath)
{
    if (m_iniPath == absoluteFilePath) {
        return; // 路径未变化
    }

    QFileInfo fileInfo(absoluteFilePath);
    QDir dir = fileInfo.dir();
    if (!dir.exists()) {
        dir.mkpath(".");
    }

    m_iniPath = absoluteFilePath;

    if (m_ini) {
        m_ini->sync();
        delete m_ini;
    }

    m_ini = new QSettings(m_iniPath, QSettings::IniFormat, this);
    load();
}

SysEnv::SysEnv(QObject* parent)
    : QObject(parent)
{
    // 使用默认路径初始化 QSettings
    m_ini = new QSettings(QSettings::IniFormat,
                          QSettings::UserScope,
                          "MyCompany", "MyApp", this);
    load();
}

// SysEnv.cpp
/* ---------- 加载 ---------- */
void SysEnv::load()
{
    if (!m_ini) {
        return;
    }
    // 基本配置
    m_cfg.serverIP   = m_ini->value("Net/ServerIP", DEFAULT_SERVER_IP).toString();
    m_cfg.serverPort = m_ini->value("Net/ServerPort", DEFAULT_SERVER_PORT).toInt();
    m_cfg.theme      = m_ini->value("UI/Theme", DEFAULT_THEME).toString();
    m_cfg.imageSavePath = m_ini->value("Save/ImagePath", DEFAULT_IMAGE_SAVE_PATH).toString();
    // 加载数据库连接配置
    m_cfg.useDatabaseParams = m_ini->value("Database/UseAlgorithmParams", true).toBool();

    // 如果配置为使用数据库参数，则从数据库加载
    if (m_cfg.useDatabaseParams) {
        loadAlgorithmParamsFromDatabase();
        loadProcessParamsFromDatabase();
        return;
    }



    // 加载预处理参数
    m_cfg.preProcessPara.fRoiZMin = m_ini->value("PreProcess/fRoiZMin", 1600.0).toDouble();
    m_cfg.preProcessPara.fRoiZMax = m_ini->value("PreProcess/fRoiZMax", 1850.0).toDouble();
    m_cfg.preProcessPara.fRoiXMin = m_ini->value("PreProcess/fRoiXMin", -500.0).toDouble();
    m_cfg.preProcessPara.fRoiXMax = m_ini->value("PreProcess/fRoiXMax", 400.0).toDouble();
    m_cfg.preProcessPara.fRoiYMin = m_ini->value("PreProcess/fRoiYMin", -300.0).toDouble();
    m_cfg.preProcessPara.fRoiYMax = m_ini->value("PreProcess/fRoiYMax", 500.0).toDouble();
    m_cfg.preProcessPara.fThSeg0Dis = m_ini->value("PreProcess/fThSeg0Dis", 30.0).toDouble();
    m_cfg.preProcessPara.iThSeg0NumPtsMin = m_ini->value("PreProcess/iThSeg0NumPtsMin", 5000).toInt();
    m_cfg.preProcessPara.iThSeg0NumPtsMax = m_ini->value("PreProcess/iThSeg0NumPtsMax", 5000000).toInt();
    m_cfg.preProcessPara.fThSeg0DiameterMin = m_ini->value("PreProcess/fThSeg0DiameterMin", 300.0).toDouble();
    m_cfg.preProcessPara.fThSeg0DiameterMax = m_ini->value("PreProcess/fThSeg0DiameterMax", 3000.0).toDouble();

    // 加载新的预处理参数
    m_cfg.preProcessPara.bUseDisToPlane = m_ini->value("PreProcess/bUseDisToPlane", false).toBool();
    m_cfg.preProcessPara.fSampleDtp = m_ini->value("PreProcess/fSampleDtp", 10.0).toDouble();
    m_cfg.preProcessPara.fThSegAngleDtp = m_ini->value("PreProcess/fThSegAngleDtp", 1.5).toDouble();
    m_cfg.preProcessPara.fThSegDisDtp = m_ini->value("PreProcess/fThSegDisDtp", 10.0).toDouble();
    m_cfg.preProcessPara.fPtsSelToPlaneDisMin = m_ini->value("PreProcess/fPtsSelToPlaneDisMin", 3.0).toDouble();
    m_cfg.preProcessPara.fPtsSelToPlaneDisMax = m_ini->value("PreProcess/fPtsSelToPlaneDisMax", 100.0).toDouble();
    m_cfg.preProcessPara.fThSeg2DisDtp = m_ini->value("PreProcess/fThSeg2DisDtp", 5.0).toDouble();
    m_cfg.preProcessPara.iThSeg2NumPtsMinDtp = m_ini->value("PreProcess/iThSeg2NumPtsMinDtp", 5000).toInt();
    m_cfg.preProcessPara.iThSeg2NumPtsMaxDtp = m_ini->value("PreProcess/iThSeg2NumPtsMaxDtp", 5000000).toInt();

    // 加载缺陷检测参数 - 更新为新的参数结构
    m_cfg.defectPara.fThNZAbsVal = m_ini->value("Defect/fThNZAbsVal", 0.8).toDouble();

    // 气缸偏移参数
    m_cfg.defectPara.fQgOffsetL = m_ini->value("Defect/fQgOffsetL", 25.0).toDouble();
    m_cfg.defectPara.fQgOffsetR = m_ini->value("Defect/fQgOffsetR", 25.0).toDouble();
    m_cfg.defectPara.fQgOffsetU = m_ini->value("Defect/fQgOffsetU", 25.0).toDouble();
    m_cfg.defectPara.fQgOffsetD = m_ini->value("Defect/fQgOffsetD", 25.0).toDouble();

    // 凸起阈值参数 - 更新为新的参数名
    m_cfg.defectPara.fThBulgeLowerC = m_ini->value("Defect/fThBulgeLowerC", 1.5).toDouble();
    m_cfg.defectPara.fThBulgeHigerC = m_ini->value("Defect/fThBulgeHigerC", 3.0).toDouble();
    m_cfg.defectPara.fThBulgeLowerS = m_ini->value("Defect/fThBulgeLowerS", 1.5).toDouble();
    m_cfg.defectPara.fThBulgeHigerS = m_ini->value("Defect/fThBulgeHigerS", 3.0).toDouble();

    m_cfg.defectPara.fQgThOffset = m_ini->value("Defect/fQgThOffset", 3.0).toDouble();

    // 气缸参数 - 更新为新的结构
    m_cfg.defectPara.fQgLHOrg = m_ini->value("Defect/fQgLHOrg", 18.0).toDouble();
    m_cfg.defectPara.fQgLExCol = m_ini->value("Defect/fQgLExCol", 15.0).toDouble();
    m_cfg.defectPara.fQgLExRow = m_ini->value("Defect/fQgLExRow", 9.0).toDouble();

    m_cfg.defectPara.fQgRHOrg = m_ini->value("Defect/fQgRHOrg", 18.0).toDouble();
    m_cfg.defectPara.fQgRExCol = m_ini->value("Defect/fQgRExCol", 15.0).toDouble();
    m_cfg.defectPara.fQgRExRow = m_ini->value("Defect/fQgRExRow", 9.0).toDouble();

    m_cfg.defectPara.fQgUHOrg = m_ini->value("Defect/fQgUHOrg", 18.0).toDouble();
    m_cfg.defectPara.fQgUExCol = m_ini->value("Defect/fQgUExCol", 15.0).toDouble();
    m_cfg.defectPara.fQgUExRow = m_ini->value("Defect/fQgUExRow", 9.0).toDouble();

    m_cfg.defectPara.fQgDHOrg = m_ini->value("Defect/fQgDHOrg", 18.0).toDouble();
    m_cfg.defectPara.fQgDExCol = m_ini->value("Defect/fQgDExCol", 15.0).toDouble();
    m_cfg.defectPara.fQgDExRow = m_ini->value("Defect/fQgDExRow", 9.0).toDouble();

    m_cfg.defectPara.fRenderRangeScale = m_ini->value("Defect/fRenderRangeScale", 1.0).toDouble();
    m_cfg.defectPara.fConnectionDis = m_ini->value("Defect/fConnectionDis", 50.0).toDouble();

    // 加载路径规划参数 - 添加新参数
    m_cfg.pathPara.fDjDiamiter = m_ini->value("Path/fDjDiamiter", 80.0).toDouble();
    m_cfg.pathPara.fJgLzUpOffset = m_ini->value("Path/fJgLzUpOffset", 2.0).toDouble();
    m_cfg.pathPara.fJgDpUpOffset = m_ini->value("Path/fJgDpUpOffset", 1.5).toDouble();
    m_cfg.pathPara.iModeJgPPZStepMode = m_ini->value("Path/iModeJgPPZStepMode", 1).toInt();
    m_cfg.pathPara.fJgPPZStepFix = m_ini->value("Path/fJgPPZStepFix", 2.0).toDouble();
    m_cfg.pathPara.fJgPPZStepK = m_ini->value("Path/fJgPPZStepK", 0.5).toDouble();
    m_cfg.pathPara.fJgPPZStepB = m_ini->value("Path/fJgPPZStepB", 1.5).toDouble();

    m_cfg.pathPara.fJgPPZStepMin = m_ini->value("Path/fJgPPZStepMin", 1.0).toDouble();
    m_cfg.pathPara.fJgPPZStepMax = m_ini->value("Path/fJgPPZStepMax", 5.0).toDouble();



    m_cfg.pathPara.iModeJgPPYStepMode = m_ini->value("Path/iModeJgPPYStepMode", 0).toInt();
    m_cfg.pathPara.fJgPPYStepFix = m_ini->value("Path/fJgPPYStepFix", 70.0).toDouble();
    m_cfg.pathPara.fJgPPYStepK = m_ini->value("Path/fJgPPYStepK", 0.80).toDouble();
    m_cfg.pathPara.iModeJgPPSort = m_ini->value("Path/iModeJgPPSort", 0).toInt();
    m_cfg.pathPara.fQgSafeDis = m_ini->value("Path/fQgSafeDis", 50.0).toDouble();

    m_cfg.pathPara.fJgTdZUp = m_ini->value("Path/fJgTdZUp", 100.0).toDouble();

    m_cfg.pathPara.fOffsetCutStartPos = m_ini->value("Path/fOffsetCutStartPos", 50.0).toDouble();
    m_cfg.pathPara.fOffsetBothEndsL = m_ini->value("Path/fOffsetBothEndsL", 10.0).toDouble();
    m_cfg.pathPara.fOffsetBothEndsR = m_ini->value("Path/fOffsetBothEndsR", 10.0).toDouble();
    m_cfg.pathPara.fOffsetPtsX = m_ini->value("Path/fOffsetPtsX", 0.0).toDouble();
    m_cfg.pathPara.fOffsetPtsY = m_ini->value("Path/fOffsetPtsY", 0.0).toDouble();
    m_cfg.pathPara.fOffsetPtsZ = m_ini->value("Path/fOffsetPtsZ", 0.0).toDouble();

    // 加载相机到机器人位姿转换参数
    m_cfg.cameraToRobotPose.fTransX = m_ini->value("CameraToRobot/fTransX", 0.0).toDouble();
    m_cfg.cameraToRobotPose.fTransY = m_ini->value("CameraToRobot/fTransY", 0.0).toDouble();
    m_cfg.cameraToRobotPose.fTransZ = m_ini->value("CameraToRobot/fTransZ", 0.0).toDouble();
    m_cfg.cameraToRobotPose.fRotX = m_ini->value("CameraToRobot/fRotX", 0.0).toDouble();
    m_cfg.cameraToRobotPose.fRotY = m_ini->value("CameraToRobot/fRotY", 0.0).toDouble();
    m_cfg.cameraToRobotPose.fRotZ = m_ini->value("CameraToRobot/fRotZ", 0.0).toDouble();
    m_cfg.cameraToRobotPose.dwType = m_ini->value("CameraToRobot/dwType", 1.0).toDouble();

    // ==== 加载工艺参数 ====
    m_cfg.processParams.toolDiameter = m_ini->value("Process/toolDiameter", 80.0).toDouble();
    m_cfg.processParams.toolSpeed = m_ini->value("Process/toolSpeed", 60.0).toDouble();
    m_cfg.processParams.lineSpacing = m_ini->value("Process/lineSpacing", 0).toDouble();
    m_cfg.processParams.cuttingDepth = m_ini->value("Process/cuttingDepth", 0).toDouble();
    m_cfg.processParams.feedRate = m_ini->value("Process/feedRate", 60.0).toDouble();
    m_cfg.processParams.workpieceSurfaceHeight = m_ini->value("Process/workpieceSurfaceHeight", 0.0).toDouble();
    m_cfg.processParams.totalCuttingDepth = m_ini->value("Process/totalCuttingDepth", 0).toDouble();
    m_cfg.processParams.stepDistance = m_ini->value("Process/stepDistance", 1.0).toDouble();
    m_cfg.processParams.rapidSpeed = m_ini->value("Process/rapidSpeed", 60).toDouble();
    m_cfg.processParams.jogSpeed = m_ini->value("Process/jogSpeed", 60).toDouble();




    // 验证配置
    if (!isConfigValid()) {
        resetToDefaults();
    }
}

/* ---------- 保存 ---------- */
void SysEnv::save()
{
    if (!m_ini) {
        return;
    }

    // 验证配置 before saving
    if (!isConfigValid()) {
        return;
    }

    // 基本配置
    m_ini->setValue("Net/ServerIP", m_cfg.serverIP);
    m_ini->setValue("Net/ServerPort", m_cfg.serverPort);
    m_ini->setValue("UI/Theme", m_cfg.theme);
    m_ini->setValue("Save/ImagePath", m_cfg.imageSavePath);

    // 保存预处理参数
    m_ini->setValue("PreProcess/fRoiZMin", m_cfg.preProcessPara.fRoiZMin);
    m_ini->setValue("PreProcess/fRoiZMax", m_cfg.preProcessPara.fRoiZMax);
    m_ini->setValue("PreProcess/fRoiXMin", m_cfg.preProcessPara.fRoiXMin);
    m_ini->setValue("PreProcess/fRoiXMax", m_cfg.preProcessPara.fRoiXMax);
    m_ini->setValue("PreProcess/fRoiYMin", m_cfg.preProcessPara.fRoiYMin);
    m_ini->setValue("PreProcess/fRoiYMax", m_cfg.preProcessPara.fRoiYMax);
    m_ini->setValue("PreProcess/fThSeg0Dis", m_cfg.preProcessPara.fThSeg0Dis);
    m_ini->setValue("PreProcess/iThSeg0NumPtsMin", m_cfg.preProcessPara.iThSeg0NumPtsMin);
    m_ini->setValue("PreProcess/iThSeg0NumPtsMax", m_cfg.preProcessPara.iThSeg0NumPtsMax);
    m_ini->setValue("PreProcess/fThSeg0DiameterMin", m_cfg.preProcessPara.fThSeg0DiameterMin);
    m_ini->setValue("PreProcess/fThSeg0DiameterMax", m_cfg.preProcessPara.fThSeg0DiameterMax);

    // 保存新的预处理参数
    m_ini->setValue("PreProcess/bUseDisToPlane", m_cfg.preProcessPara.bUseDisToPlane);
    m_ini->setValue("PreProcess/fSampleDtp", m_cfg.preProcessPara.fSampleDtp);
    m_ini->setValue("PreProcess/fThSegAngleDtp", m_cfg.preProcessPara.fThSegAngleDtp);
    m_ini->setValue("PreProcess/fThSegDisDtp", m_cfg.preProcessPara.fThSegDisDtp);
    m_ini->setValue("PreProcess/fPtsSelToPlaneDisMin", m_cfg.preProcessPara.fPtsSelToPlaneDisMin);
    m_ini->setValue("PreProcess/fPtsSelToPlaneDisMax", m_cfg.preProcessPara.fPtsSelToPlaneDisMax);
    m_ini->setValue("PreProcess/fThSeg2DisDtp", m_cfg.preProcessPara.fThSeg2DisDtp);
    m_ini->setValue("PreProcess/iThSeg2NumPtsMinDtp", m_cfg.preProcessPara.iThSeg2NumPtsMinDtp);
    m_ini->setValue("PreProcess/iThSeg2NumPtsMaxDtp", m_cfg.preProcessPara.iThSeg2NumPtsMaxDtp);

    // 保存缺陷检测参数 - 更新为新的参数结构
    m_ini->setValue("Defect/fThNZAbsVal", m_cfg.defectPara.fThNZAbsVal);

    // 气缸偏移参数
    m_ini->setValue("Defect/fQgOffsetL", m_cfg.defectPara.fQgOffsetL);
    m_ini->setValue("Defect/fQgOffsetR", m_cfg.defectPara.fQgOffsetR);
    m_ini->setValue("Defect/fQgOffsetU", m_cfg.defectPara.fQgOffsetU);
    m_ini->setValue("Defect/fQgOffsetD", m_cfg.defectPara.fQgOffsetD);

    // 凸起阈值参数 - 更新为新的参数名
    m_ini->setValue("Defect/fThBulgeLowerC", m_cfg.defectPara.fThBulgeLowerC);
    m_ini->setValue("Defect/fThBulgeHigerC", m_cfg.defectPara.fThBulgeHigerC);
    m_ini->setValue("Defect/fThBulgeLowerS", m_cfg.defectPara.fThBulgeLowerS);
    m_ini->setValue("Defect/fThBulgeHigerS", m_cfg.defectPara.fThBulgeHigerS);

    m_ini->setValue("Defect/fQgThOffset", m_cfg.defectPara.fQgThOffset);

    // 气缸参数 - 更新为新的结构
    m_ini->setValue("Defect/fQgLHOrg", m_cfg.defectPara.fQgLHOrg);
    m_ini->setValue("Defect/fQgLExCol", m_cfg.defectPara.fQgLExCol);
    m_ini->setValue("Defect/fQgLExRow", m_cfg.defectPara.fQgLExRow);

    m_ini->setValue("Defect/fQgRHOrg", m_cfg.defectPara.fQgRHOrg);
    m_ini->setValue("Defect/fQgRExCol", m_cfg.defectPara.fQgRExCol);
    m_ini->setValue("Defect/fQgRExRow", m_cfg.defectPara.fQgRExRow);

    m_ini->setValue("Defect/fQgUHOrg", m_cfg.defectPara.fQgUHOrg);
    m_ini->setValue("Defect/fQgUExCol", m_cfg.defectPara.fQgUExCol);
    m_ini->setValue("Defect/fQgUExRow", m_cfg.defectPara.fQgUExRow);

    m_ini->setValue("Defect/fQgDHOrg", m_cfg.defectPara.fQgDHOrg);
    m_ini->setValue("Defect/fQgDExCol", m_cfg.defectPara.fQgDExCol);
    m_ini->setValue("Defect/fQgDExRow", m_cfg.defectPara.fQgDExRow);

    m_ini->setValue("Defect/fRenderRangeScale", m_cfg.defectPara.fRenderRangeScale);
    m_ini->setValue("Defect/fConnectionDis", m_cfg.defectPara.fConnectionDis);

    // 保存路径规划参数 - 添加新参数
    m_ini->setValue("Path/fDjDiamiter", m_cfg.pathPara.fDjDiamiter);
    m_ini->setValue("Path/fJgLzUpOffset", m_cfg.pathPara.fJgLzUpOffset);
    m_ini->setValue("Path/fJgDpUpOffset", m_cfg.pathPara.fJgDpUpOffset);
    m_ini->setValue("Path/iModeJgPPZStepMode", m_cfg.pathPara.iModeJgPPZStepMode);
    m_ini->setValue("Path/fJgPPZStepFix", m_cfg.pathPara.fJgPPZStepFix);
    m_ini->setValue("Path/fJgPPZStepK", m_cfg.pathPara.fJgPPZStepK);
    m_ini->setValue("Path/fJgPPZStepB", m_cfg.pathPara.fJgPPZStepB);


    m_ini->setValue("Path/fJgPPZStepMin", m_cfg.pathPara.fJgPPZStepMin);
    m_ini->setValue("Path/fJgPPZStepMax", m_cfg.pathPara.fJgPPZStepMax);

    m_ini->setValue("Path/iModeJgPPYStepMode", m_cfg.pathPara.iModeJgPPYStepMode);
    m_ini->setValue("Path/fJgPPYStepFix", m_cfg.pathPara.fJgPPYStepFix);
    m_ini->setValue("Path/fJgPPYStepK", m_cfg.pathPara.fJgPPYStepK);
    m_ini->setValue("Path/iModeJgPPSort", m_cfg.pathPara.iModeJgPPSort);
    m_ini->setValue("Path/fQgSafeDis", m_cfg.pathPara.fQgSafeDis);

    m_ini->setValue("Path/fJgTdZUp", m_cfg.pathPara.fJgTdZUp);

    m_ini->setValue("Path/fOffsetCutStartPos", m_cfg.pathPara.fOffsetCutStartPos);
    m_ini->setValue("Path/fOffsetBothEndsL", m_cfg.pathPara.fOffsetBothEndsL);
    m_ini->setValue("Path/fOffsetBothEndsR", m_cfg.pathPara.fOffsetBothEndsR);
    m_ini->setValue("Path/fOffsetPtsX", m_cfg.pathPara.fOffsetPtsX);
    m_ini->setValue("Path/fOffsetPtsY", m_cfg.pathPara.fOffsetPtsY);
    m_ini->setValue("Path/fOffsetPtsZ", m_cfg.pathPara.fOffsetPtsZ);

    // 保存相机到机器人位姿转换参数
    m_ini->setValue("CameraToRobot/fTransX", m_cfg.cameraToRobotPose.fTransX);
    m_ini->setValue("CameraToRobot/fTransY", m_cfg.cameraToRobotPose.fTransY);
    m_ini->setValue("CameraToRobot/fTransZ", m_cfg.cameraToRobotPose.fTransZ);
    m_ini->setValue("CameraToRobot/fRotX", m_cfg.cameraToRobotPose.fRotX);
    m_ini->setValue("CameraToRobot/fRotY", m_cfg.cameraToRobotPose.fRotY);
    m_ini->setValue("CameraToRobot/fRotZ", m_cfg.cameraToRobotPose.fRotZ);
    m_ini->setValue("CameraToRobot/dwType", m_cfg.cameraToRobotPose.dwType);

    // ==== 保存工艺参数 ====
    m_ini->setValue("Process/toolDiameter", m_cfg.processParams.toolDiameter);
    m_ini->setValue("Process/toolSpeed", m_cfg.processParams.toolSpeed);
    m_ini->setValue("Process/lineSpacing", m_cfg.processParams.lineSpacing);
    m_ini->setValue("Process/cuttingDepth", m_cfg.processParams.cuttingDepth);
    m_ini->setValue("Process/feedRate", m_cfg.processParams.feedRate);
    m_ini->setValue("Process/workpieceSurfaceHeight", m_cfg.processParams.workpieceSurfaceHeight);
    m_ini->setValue("Process/totalCuttingDepth", m_cfg.processParams.totalCuttingDepth);
    m_ini->setValue("Process/stepDistance", m_cfg.processParams.stepDistance);
    m_ini->setValue("Process/rapidSpeed", m_cfg.processParams.rapidSpeed);
    m_ini->setValue("Process/jogSpeed", m_cfg.processParams.jogSpeed);

    // 保存数据库连接配置
    m_ini->setValue("Database/UseAlgorithmParams", m_cfg.useDatabaseParams);

    m_ini->sync();
    emit cfgChanged();
}

// 从数据库加载算法参数
bool SysEnv::loadAlgorithmParamsFromDatabase()
{
    // 初始化数据库连接
    DatabaseManager& dbManager = DatabaseManager::instance();
    QVariantMap result = dbManager.selectCategory("algorithm");


    if (result.isEmpty()) {
        emit algorithmParamsLoaded(false, "未找到算法参数配置");
        qDebug() << "未找到算法参数配置";
        return false;
    }

    // 获取payload JSON字段
    QVariant payloadVariant = result["payload"];
    QString jsonString = payloadVariant.toString();

    QJsonDocument doc = QJsonDocument::fromJson(jsonString.toUtf8());
    if (!doc.isObject()) {
        emit algorithmParamsLoaded(false, "payload不是有效的JSON格式");
        return false;
    }

    QJsonObject algorithmJson = doc.object();
    m_algorithmJson = algorithmJson;

    // 解析JSON到具体结构体
    bool parseSuccess = parseAlgorithmJson(algorithmJson);

    if (parseSuccess) {
        m_rt.algorithmSource = ConfigSource::Database;
        emit algorithmParamsLoaded(true, "算法参数从数据库加载成功");
        emit algorithmSourceChanged(ConfigSource::Database);
    } else {
        emit algorithmParamsLoaded(false, "算法参数解析失败");
    }

    return parseSuccess;
}

// 解析算法参数JSON
bool SysEnv::parseAlgorithmJson(const QJsonObject& json)
{
    try {
        // 解析预处理参数
        if (json.contains("pre_process")) {
            QJsonObject preProcessJson = json["pre_process"].toObject();

            // ROI参数
            if (preProcessJson.contains("roi")) {
                QJsonObject roiJson = preProcessJson["roi"].toObject();
                m_cfg.preProcessPara.fRoiZMin = roiJson["z_min"].toDouble();
                m_cfg.preProcessPara.fRoiZMax = roiJson["z_max"].toDouble();
                m_cfg.preProcessPara.fRoiXMin = roiJson["x_min"].toDouble();
                m_cfg.preProcessPara.fRoiXMax = roiJson["x_max"].toDouble();
                m_cfg.preProcessPara.fRoiYMin = roiJson["y_min"].toDouble();
                m_cfg.preProcessPara.fRoiYMax = roiJson["y_max"].toDouble();
            }

            // 分割参数
            if (preProcessJson.contains("segmentation")) {
                QJsonObject segJson = preProcessJson["segmentation"].toObject();
                m_cfg.preProcessPara.fThSeg0Dis = segJson["distance"].toDouble();
                m_cfg.preProcessPara.iThSeg0NumPtsMin = segJson["min_points"].toInt();
                m_cfg.preProcessPara.iThSeg0NumPtsMax = segJson["max_points"].toInt();
                m_cfg.preProcessPara.fThSeg0DiameterMin = segJson["diameter_min"].toDouble();
                m_cfg.preProcessPara.fThSeg0DiameterMax = segJson["diameter_max"].toDouble();
            }

            // 平面距离参数
            if (preProcessJson.contains("plane_distance")) {
                QJsonObject planeJson = preProcessJson["plane_distance"].toObject();
                m_cfg.preProcessPara.bUseDisToPlane = planeJson["enabled"].toBool();
                m_cfg.preProcessPara.fSampleDtp = planeJson["sample_distance"].toDouble();
                m_cfg.preProcessPara.fThSegAngleDtp = planeJson["angle_threshold"].toDouble();
                m_cfg.preProcessPara.fThSegDisDtp = planeJson["distance_threshold"].toDouble();
                m_cfg.preProcessPara.fPtsSelToPlaneDisMin = planeJson["plane_distance_min"].toDouble();
                m_cfg.preProcessPara.fPtsSelToPlaneDisMax = planeJson["plane_distance_max"].toDouble();
            }

            // 聚类参数
            if (preProcessJson.contains("clustering")) {
                QJsonObject clusterJson = preProcessJson["clustering"].toObject();
                m_cfg.preProcessPara.fThSeg2DisDtp = clusterJson["distance_threshold"].toDouble();
                m_cfg.preProcessPara.iThSeg2NumPtsMinDtp = clusterJson["min_points"].toInt();
                m_cfg.preProcessPara.iThSeg2NumPtsMaxDtp = clusterJson["max_points"].toInt();
            }
        }

        // 解析缺陷检测参数
        if (json.contains("defect")) {
            QJsonObject defectJson = json["defect"].toObject();

            m_cfg.defectPara.fThNZAbsVal = defectJson["normal_threshold"].toDouble();

            // 气缸偏移
            if (defectJson.contains("cylinder_offset")) {
                QJsonObject offsetJson = defectJson["cylinder_offset"].toObject();
                m_cfg.defectPara.fQgOffsetL = offsetJson["left"].toDouble();
                m_cfg.defectPara.fQgOffsetR = offsetJson["right"].toDouble();
                m_cfg.defectPara.fQgOffsetU = offsetJson["up"].toDouble();
                m_cfg.defectPara.fQgOffsetD = offsetJson["down"].toDouble();
            }

            // 凸起阈值
            if (defectJson.contains("bulge_thresholds")) {
                QJsonObject bulgeJson = defectJson["bulge_thresholds"].toObject();
                m_cfg.defectPara.fThBulgeLowerC = bulgeJson["center_low"].toDouble();
                m_cfg.defectPara.fThBulgeHigerC = bulgeJson["center_high"].toDouble();
                m_cfg.defectPara.fThBulgeLowerS = bulgeJson["edge_low"].toDouble();
                m_cfg.defectPara.fThBulgeHigerS = bulgeJson["edge_high"].toDouble();
            }

            m_cfg.defectPara.fQgThOffset = defectJson["cylinder_height_threshold"].toDouble();

            // 气缸参数
            if (defectJson.contains("cylinders")) {
                QJsonObject cylindersJson = defectJson["cylinders"].toObject();

                if (cylindersJson.contains("left")) {
                    QJsonObject leftJson = cylindersJson["left"].toObject();
                    m_cfg.defectPara.fQgLHOrg = leftJson["height_origin"].toDouble();
                    m_cfg.defectPara.fQgLExCol = leftJson["extend_x"].toDouble();
                    m_cfg.defectPara.fQgLExRow = leftJson["extend_y"].toDouble();
                }

                if (cylindersJson.contains("right")) {
                    QJsonObject rightJson = cylindersJson["right"].toObject();
                    m_cfg.defectPara.fQgRHOrg = rightJson["height_origin"].toDouble();
                    m_cfg.defectPara.fQgRExCol = rightJson["extend_x"].toDouble();
                    m_cfg.defectPara.fQgRExRow = rightJson["extend_y"].toDouble();
                }

                if (cylindersJson.contains("up")) {
                    QJsonObject upJson = cylindersJson["up"].toObject();
                    m_cfg.defectPara.fQgUHOrg = upJson["height_origin"].toDouble();
                    m_cfg.defectPara.fQgUExCol = upJson["extend_x"].toDouble();
                    m_cfg.defectPara.fQgUExRow = upJson["extend_y"].toDouble();
                }

                if (cylindersJson.contains("down")) {
                    QJsonObject downJson = cylindersJson["down"].toObject();
                    m_cfg.defectPara.fQgDHOrg = downJson["height_origin"].toDouble();
                    m_cfg.defectPara.fQgDExCol = downJson["extend_x"].toDouble();
                    m_cfg.defectPara.fQgDExRow = downJson["extend_y"].toDouble();
                }
            }

            m_cfg.defectPara.fRenderRangeScale = defectJson["render_range_scale"].toDouble();
            m_cfg.defectPara.fConnectionDis = defectJson["connection_distance"].toDouble();
        }

        // 解析路径规划参数
        if (json.contains("path_planning")) {
            QJsonObject pathJson = json["path_planning"].toObject();

            m_cfg.pathPara.fDjDiamiter = pathJson["tool_diameter"].toDouble();
            m_cfg.pathPara.fJgLzUpOffset = pathJson["particle_peak_offset"].toDouble();
            m_cfg.pathPara.fJgDpUpOffset = pathJson["plate_offset"].toDouble();
            m_cfg.pathPara.iModeJgPPZStepMode = pathJson["z_step_mode"].toInt();
            m_cfg.pathPara.fJgPPZStepFix = pathJson["z_step_fixed"].toDouble();
            m_cfg.pathPara.fJgPPZStepK = pathJson["z_step_linear_k"].toDouble();
            m_cfg.pathPara.fJgPPZStepB = pathJson["z_step_linear_b"].toDouble();
            m_cfg.pathPara.fJgPPZStepMin = pathJson["z_step_min"].toDouble();
            m_cfg.pathPara.fJgPPZStepMax = pathJson["z_step_max"].toDouble();
            m_cfg.pathPara.iModeJgPPYStepMode = pathJson["y_step_mode"].toInt();
            m_cfg.pathPara.fJgPPYStepFix = pathJson["y_step_fixed"].toDouble();
            m_cfg.pathPara.fJgPPYStepK = pathJson["y_step_coeff"].toDouble();
            m_cfg.pathPara.iModeJgPPSort = pathJson["sort_mode"].toInt();
            m_cfg.pathPara.fQgSafeDis = pathJson["cylinder_safe_distance"].toDouble();
            m_cfg.pathPara.fJgTdZUp = pathJson["lift_height"].toDouble();
            m_cfg.pathPara.fOffsetCutStartPos = pathJson["cut_start_offset"].toDouble();
            m_cfg.pathPara.fOffsetBothEndsL = pathJson["end_offset_left"].toDouble();
            m_cfg.pathPara.fOffsetBothEndsR = pathJson["end_offset_right"].toDouble();

            if (pathJson.contains("offset")) {
                QJsonObject offsetJson = pathJson["offset"].toObject();
                m_cfg.pathPara.fOffsetPtsX = offsetJson["x"].toDouble();
                m_cfg.pathPara.fOffsetPtsY = offsetJson["y"].toDouble();
                m_cfg.pathPara.fOffsetPtsZ = offsetJson["z"].toDouble();
            }
        }

        // 解析位姿变换参数
        if (json.contains("pose_transform")) {
            QJsonObject poseJson = json["pose_transform"].toObject();

            if (poseJson.contains("translation")) {
                QJsonObject transJson = poseJson["translation"].toObject();
                m_cfg.cameraToRobotPose.fTransX = transJson["x"].toDouble();
                m_cfg.cameraToRobotPose.fTransY = transJson["y"].toDouble();
                m_cfg.cameraToRobotPose.fTransZ = transJson["z"].toDouble();
            }

            if (poseJson.contains("rotation")) {
                QJsonObject rotJson = poseJson["rotation"].toObject();
                m_cfg.cameraToRobotPose.fRotX = rotJson["x"].toDouble();
                m_cfg.cameraToRobotPose.fRotY = rotJson["y"].toDouble();
                m_cfg.cameraToRobotPose.fRotZ = rotJson["z"].toDouble();
            }

            m_cfg.cameraToRobotPose.dwType = poseJson["type"].toInt();
        }

        return true;

    } catch (const std::exception& e) {
        qCritical() << "解析算法参数时发生异常:" << e.what();
        return false;
    }
}

// 将当前参数转换为JSON
QJsonObject SysEnv::algorithmParamsToJson() const
{
    QJsonObject json;

    // 预处理参数
    QJsonObject preProcess;
    QJsonObject roi;
    roi["z_min"] = m_cfg.preProcessPara.fRoiZMin;
    roi["z_max"] = m_cfg.preProcessPara.fRoiZMax;
    roi["x_min"] = m_cfg.preProcessPara.fRoiXMin;
    roi["x_max"] = m_cfg.preProcessPara.fRoiXMax;
    roi["y_min"] = m_cfg.preProcessPara.fRoiYMin;
    roi["y_max"] = m_cfg.preProcessPara.fRoiYMax;
    preProcess["roi"] = roi;

    QJsonObject segmentation;
    segmentation["distance"] = m_cfg.preProcessPara.fThSeg0Dis;
    segmentation["min_points"] = m_cfg.preProcessPara.iThSeg0NumPtsMin;
    segmentation["max_points"] = m_cfg.preProcessPara.iThSeg0NumPtsMax;
    segmentation["diameter_min"] = m_cfg.preProcessPara.fThSeg0DiameterMin;
    segmentation["diameter_max"] = m_cfg.preProcessPara.fThSeg0DiameterMax;
    preProcess["segmentation"] = segmentation;

    QJsonObject planeDistance;
    planeDistance["enabled"] = m_cfg.preProcessPara.bUseDisToPlane;
    planeDistance["sample_distance"] = m_cfg.preProcessPara.fSampleDtp;
    planeDistance["angle_threshold"] = m_cfg.preProcessPara.fThSegAngleDtp;
    planeDistance["distance_threshold"] = m_cfg.preProcessPara.fThSegDisDtp;
    planeDistance["plane_distance_min"] = m_cfg.preProcessPara.fPtsSelToPlaneDisMin;
    planeDistance["plane_distance_max"] = m_cfg.preProcessPara.fPtsSelToPlaneDisMax;
    preProcess["plane_distance"] = planeDistance;

    QJsonObject clustering;
    clustering["distance_threshold"] = m_cfg.preProcessPara.fThSeg2DisDtp;
    clustering["min_points"] = m_cfg.preProcessPara.iThSeg2NumPtsMinDtp;
    clustering["max_points"] = m_cfg.preProcessPara.iThSeg2NumPtsMaxDtp;
    preProcess["clustering"] = clustering;

    json["pre_process"] = preProcess;

    // 缺陷检测参数
    QJsonObject defect;
    defect["normal_threshold"] = m_cfg.defectPara.fThNZAbsVal;

    QJsonObject cylinderOffset;
    cylinderOffset["left"] = m_cfg.defectPara.fQgOffsetL;
    cylinderOffset["right"] = m_cfg.defectPara.fQgOffsetR;
    cylinderOffset["up"] = m_cfg.defectPara.fQgOffsetU;
    cylinderOffset["down"] = m_cfg.defectPara.fQgOffsetD;
    defect["cylinder_offset"] = cylinderOffset;

    QJsonObject bulgeThresholds;
    bulgeThresholds["center_low"] = m_cfg.defectPara.fThBulgeLowerC;
    bulgeThresholds["center_high"] = m_cfg.defectPara.fThBulgeHigerC;
    bulgeThresholds["edge_low"] = m_cfg.defectPara.fThBulgeLowerS;
    bulgeThresholds["edge_high"] = m_cfg.defectPara.fThBulgeHigerS;
    defect["bulge_thresholds"] = bulgeThresholds;

    defect["cylinder_height_threshold"] = m_cfg.defectPara.fQgThOffset;

    QJsonObject cylinders;
    QJsonObject leftCylinder;
    leftCylinder["height_origin"] = m_cfg.defectPara.fQgLHOrg;
    leftCylinder["extend_x"] = m_cfg.defectPara.fQgLExCol;
    leftCylinder["extend_y"] = m_cfg.defectPara.fQgLExRow;
    cylinders["left"] = leftCylinder;

    QJsonObject rightCylinder;
    rightCylinder["height_origin"] = m_cfg.defectPara.fQgRHOrg;
    rightCylinder["extend_x"] = m_cfg.defectPara.fQgRExCol;
    rightCylinder["extend_y"] = m_cfg.defectPara.fQgRExRow;
    cylinders["right"] = rightCylinder;

    QJsonObject upCylinder;
    upCylinder["height_origin"] = m_cfg.defectPara.fQgUHOrg;
    upCylinder["extend_x"] = m_cfg.defectPara.fQgUExCol;
    upCylinder["extend_y"] = m_cfg.defectPara.fQgUExRow;
    cylinders["up"] = upCylinder;

    QJsonObject downCylinder;
    downCylinder["height_origin"] = m_cfg.defectPara.fQgDHOrg;
    downCylinder["extend_x"] = m_cfg.defectPara.fQgDExCol;
    downCylinder["extend_y"] = m_cfg.defectPara.fQgDExRow;
    cylinders["down"] = downCylinder;

    defect["cylinders"] = cylinders;
    defect["render_range_scale"] = m_cfg.defectPara.fRenderRangeScale;
    defect["connection_distance"] = m_cfg.defectPara.fConnectionDis;

    json["defect"] = defect;

    // 路径规划参数
    QJsonObject pathPlanning;
    pathPlanning["tool_diameter"] = m_cfg.pathPara.fDjDiamiter;
    pathPlanning["particle_peak_offset"] = m_cfg.pathPara.fJgLzUpOffset;
    pathPlanning["plate_offset"] = m_cfg.pathPara.fJgDpUpOffset;
    pathPlanning["z_step_mode"] = m_cfg.pathPara.iModeJgPPZStepMode;
    pathPlanning["z_step_fixed"] = m_cfg.pathPara.fJgPPZStepFix;
    pathPlanning["z_step_linear_k"] = m_cfg.pathPara.fJgPPZStepK;
    pathPlanning["z_step_linear_b"] = m_cfg.pathPara.fJgPPZStepB;
    pathPlanning["z_step_min"] = m_cfg.pathPara.fJgPPZStepMin;
    pathPlanning["z_step_max"] = m_cfg.pathPara.fJgPPZStepMax;
    pathPlanning["y_step_mode"] = m_cfg.pathPara.iModeJgPPYStepMode;
    pathPlanning["y_step_fixed"] = m_cfg.pathPara.fJgPPYStepFix;
    pathPlanning["y_step_coeff"] = m_cfg.pathPara.fJgPPYStepK;
    pathPlanning["sort_mode"] = m_cfg.pathPara.iModeJgPPSort;
    pathPlanning["cylinder_safe_distance"] = m_cfg.pathPara.fQgSafeDis;
    pathPlanning["lift_height"] = m_cfg.pathPara.fJgTdZUp;
    pathPlanning["cut_start_offset"] = m_cfg.pathPara.fOffsetCutStartPos;
    pathPlanning["end_offset_left"] = m_cfg.pathPara.fOffsetBothEndsL;
    pathPlanning["end_offset_right"] = m_cfg.pathPara.fOffsetBothEndsR;

    QJsonObject offset;
    offset["x"] = m_cfg.pathPara.fOffsetPtsX;
    offset["y"] = m_cfg.pathPara.fOffsetPtsY;
    offset["z"] = m_cfg.pathPara.fOffsetPtsZ;
    pathPlanning["offset"] = offset;

    json["path_planning"] = pathPlanning;

    // 位姿变换参数
    QJsonObject poseTransform;
    QJsonObject translation;
    translation["x"] = m_cfg.cameraToRobotPose.fTransX;
    translation["y"] = m_cfg.cameraToRobotPose.fTransY;
    translation["z"] = m_cfg.cameraToRobotPose.fTransZ;
    poseTransform["translation"] = translation;

    QJsonObject rotation;
    rotation["x"] = m_cfg.cameraToRobotPose.fRotX;
    rotation["y"] = m_cfg.cameraToRobotPose.fRotY;
    rotation["z"] = m_cfg.cameraToRobotPose.fRotZ;
    poseTransform["rotation"] = rotation;

    poseTransform["type"] = static_cast<int>(m_cfg.cameraToRobotPose.dwType);

    json["pose_transform"] = poseTransform;

    return json;
}

// 获取算法参数JSON
QJsonObject SysEnv::getAlgorithmParamsJson() const
{
    return m_algorithmJson;
}

// 从数据库加载工艺参数
bool SysEnv::loadProcessParamsFromDatabase()
{
    // 初始化数据库连接
    DatabaseManager& dbManager = DatabaseManager::instance();

    // 查询工艺参数
    QVariantMap result = dbManager.selectCategory("process");

    if (result.isEmpty()) {
        emit processParamsLoaded(false, "未找到工艺参数配置");
        qDebug() << "未找到工艺参数配置";
        return false;
    }

    // 获取payload JSON字段
    QVariant payloadVariant = result["payload"];
    QString jsonString = payloadVariant.toString();

    QJsonDocument doc = QJsonDocument::fromJson(jsonString.toUtf8());
    if (!doc.isObject()) {
        emit processParamsLoaded(false, "payload不是有效的JSON格式");
        return false;
    }

    QJsonObject processJson = doc.object();

    // 解析JSON到工艺参数结构体
    bool parseSuccess = parseProcessParamsJson(processJson);

    if (parseSuccess) {
        emit processParamsLoaded(true, "工艺参数从数据库加载成功");
    } else {
        emit processParamsLoaded(false, "工艺参数解析失败");
    }

    return parseSuccess;
}

// 解析工艺参数JSON
bool SysEnv::parseProcessParamsJson(const QJsonObject& json)
{
    try {
        // 解析运动参数
        if (json.contains("motion")) {
            QJsonObject motionJson = json["motion"].toObject();
            m_cfg.processParams.rapidSpeed = motionJson["rapidSpeed"].toDouble();
            m_cfg.processParams.stepDistance = motionJson["stepDistance"].toDouble();
            m_cfg.processParams.feedRate = motionJson["feed_speed"].toDouble();
            m_cfg.processParams.workpieceSurfaceHeight = motionJson["workpieceSurfaceHeight"].toDouble();
            m_cfg.processParams.jogSpeed = motionJson["jogSpeed"].toDouble();
        }

        // 解析主轴参数
        if (json.contains("spindle")) {
            QJsonObject spindleJson = json["spindle"].toObject();
            m_cfg.processParams.toolSpeed = spindleJson["rpm"].toDouble();
            m_cfg.processParams.toolDiameter = spindleJson["tool_diameter"].toDouble();
            m_cfg.processParams.lineSpacing = spindleJson["lineSpacing"].toDouble();
            m_cfg.processParams.cuttingDepth = spindleJson["cuttingDepth"].toDouble();
            m_cfg.processParams.feedRate = spindleJson["feedRate"].toDouble();
        }

        return true;

    } catch (const std::exception& e) {
        qCritical() << "解析工艺参数时发生异常:" << e.what();
        return false;
    }
}

// 保存算法参数到数据库（简化版）
bool SysEnv::saveAlgorithmParamsToDatabase()
{
    DatabaseManager& dbManager = DatabaseManager::instance();

    // 将当前参数转换为JSON
    QJsonObject algorithmJson = algorithmParamsToJson();

    // 准备数据
    QVariantMap data;
    data["category"] = "algorithm";
    data["payload"] = algorithmJson;
    data["updated_by"] = "System";

    // 使用replaceData确保只有一条记录
    bool success = dbManager.replaceData("param_settings", data);

    if (success) {
        m_algorithmJson = algorithmJson;
        m_rt.algorithmSource = ConfigSource::Database;
        emit algorithmSourceChanged(ConfigSource::Database);
    }

    return success;
}

void SysEnv::setRunning(bool on)
{
    if (m_rt.running == on) {
        return;
    }
    m_rt.running = on;
    emit runningChanged(on);
}

QString SysEnv::getImageSavePath() const
{
    if (m_cfg.imageSavePath.isEmpty()) {
        // 如果未设置，返回默认路径（应用程序目录下的capture_root）
        return QCoreApplication::applicationDirPath() + "/capture_root";
    }
    return m_cfg.imageSavePath;
}

void SysEnv::setImageSavePath(const QString &path)
{
    if (m_cfg.imageSavePath == path) {
        return;
    }

    m_cfg.imageSavePath = path;
    save();
}

void SysEnv::setBit(quint8 bit, bool bad)
{
    quint8 old = m_rt.initMask;
    if (bad) {
        m_rt.initMask |= bit;
    } else {
        m_rt.initMask &= ~bit;
    }

    if (old != m_rt.initMask) {
        emit initDone(m_rt.initMask);
    }
}

void SysEnv::resetToDefaults()
{
    // 基本配置
    m_cfg.serverIP = DEFAULT_SERVER_IP;
    m_cfg.serverPort = DEFAULT_SERVER_PORT;
    m_cfg.theme = DEFAULT_THEME;
    m_cfg.imageSavePath = DEFAULT_IMAGE_SAVE_PATH;

    // 处理参数为DataX.h中的默认值
    m_cfg.preProcessPara = s_PreProcess3DSPara();
    m_cfg.defectPara = s_DefectPlateBPara();
    m_cfg.pathPara = s_JggyPara();

    // 设置特定的默认值
    m_cfg.preProcessPara.fRoiZMin = 1600.0;
    m_cfg.preProcessPara.fRoiZMax = 1780.0;
    m_cfg.preProcessPara.fRoiXMin = -900.0;
    m_cfg.preProcessPara.fRoiXMax = 550.0;
    m_cfg.preProcessPara.fRoiYMin = -800.0;
    m_cfg.preProcessPara.fRoiYMax = 800.0;
    m_cfg.preProcessPara.fThSeg0Dis = 80.000;
    m_cfg.preProcessPara.iThSeg0NumPtsMin = 5000;
    m_cfg.preProcessPara.iThSeg0NumPtsMax = 5000000;
    m_cfg.preProcessPara.fThSeg0DiameterMin = 300.0;
    m_cfg.preProcessPara.fThSeg0DiameterMax = 3000.0;

    // 缺陷检测参数默认值
    m_cfg.defectPara.fThNZAbsVal = 0.8;
    m_cfg.defectPara.fQgOffsetL = 25.0;
    m_cfg.defectPara.fQgOffsetR = 25.0;
    m_cfg.defectPara.fQgOffsetU = 25.0;
    m_cfg.defectPara.fQgOffsetD = 25.0;
    m_cfg.defectPara.fThBulgeLowerC = 1.5;
    m_cfg.defectPara.fThBulgeHigerC = 3.0;
    m_cfg.defectPara.fThBulgeLowerS = 3.0;
    m_cfg.defectPara.fThBulgeHigerS = 4.0;
    m_cfg.defectPara.fQgThOffset = 4.5;

    m_cfg.defectPara.fQgLHOrg = 50.0;
    m_cfg.defectPara.fQgLExCol = 35.0;
    m_cfg.defectPara.fQgLExRow = 21.0;

    m_cfg.defectPara.fQgRHOrg = 51.0;
    m_cfg.defectPara.fQgRExCol = 35.0;
    m_cfg.defectPara.fQgRExRow = 21.0;

    m_cfg.defectPara.fQgUHOrg = 50.0;
    m_cfg.defectPara.fQgUExCol = 25.0;
    m_cfg.defectPara.fQgUExRow = 35.0;

    m_cfg.defectPara.fQgDHOrg = 50.0;
    m_cfg.defectPara.fQgDExCol = 25.0;
    m_cfg.defectPara.fQgDExRow = 35.0;

    m_cfg.defectPara.fRenderRangeScale = 10.0;
    m_cfg.defectPara.fConnectionDis = 80.0;

    // 路径规划参数默认值
    m_cfg.pathPara.fDjDiamiter=80;  //刀具直径
    m_cfg.pathPara.fJgLzUpOffset=2.0;  //粒子最高点上抬距离 作为最高点
    m_cfg.pathPara.fJgDpUpOffset=1.5; //铜板上平面上抬距离作为最低点
    m_cfg.pathPara.iModeJgPPZStepMode=1;//规划Z路径进给模式  0 :等距进给 1：线性进给
    m_cfg.pathPara.fJgPPZStepFix=2.0;  //固定进给Z
    m_cfg.pathPara.fJgPPZStepK=0.5;    //线性进给Z的直线系数 K B
    m_cfg.pathPara.fJgPPZStepB=1.5;

    m_cfg.pathPara.fJgPPZStepMin=3.0;   //线性进给Z最小值
    m_cfg.pathPara.fJgPPZStepMax=8.0;   //线性进给Z最大值


    m_cfg.pathPara.iModeJgPPYStepMode=0; //规划Y路径进给模式  0 :固定进给 2：根据刀盘大小进给
    m_cfg.pathPara.fJgPPYStepFix=70;   //固定进给距离
    m_cfg.pathPara.fJgPPYStepK=0.8;    //线性进给距离--刀盘直径系数
    m_cfg.pathPara.iModeJgPPSort=0;   //粒子加工排序 0：从上到下  1 ：从左到右   目前都存在明显的弊端 需进一步优化
    m_cfg.pathPara.fQgSafeDis=60;  //气缸安全距离  注意此处考虑的是加工中心点到气缸的安全距离，未考虑刀盘直径影响

    m_cfg.pathPara.fJgTdZUp=100;    //抬刀高度 用于起始点 或者终点 加工完后的上抬高度

    m_cfg.pathPara.fOffsetCutStartPos=50; //下刀位置偏移
    m_cfg.pathPara.fOffsetBothEndsL=10; //路径段左偏移
    m_cfg.pathPara.fOffsetBothEndsR=10;//路径段右偏移


    m_cfg.pathPara.fOffsetPtsX = 0; //路径点整体偏移X  --机床坐标系下的补偿 补偿方向和机床坐标系一致
    m_cfg.pathPara.fOffsetPtsY = 0; //路径点整体偏移Y
    m_cfg.pathPara.fOffsetPtsZ = 0; //路径点整体偏移Z   测试时 将Z加一个较大向上高度 便于观察路径点是否准确 精调时 可以用作略微修正Z轴坐标（±2mm以内）


    // ==== 设置工艺参数默认值 ====
    m_cfg.processParams.toolDiameter = 80.0;
    m_cfg.processParams.toolSpeed = 60.0;
    m_cfg.processParams.lineSpacing = 0;
    m_cfg.processParams.cuttingDepth = 0;
    m_cfg.processParams.feedRate = 60.0;
    m_cfg.processParams.workpieceSurfaceHeight = 0.0;
    m_cfg.processParams.totalCuttingDepth = 0;
    m_cfg.processParams.stepDistance = 1.0;
    m_cfg.processParams.rapidSpeed = 60;
    m_cfg.processParams.jogSpeed = 60;

    save();
}

bool SysEnv::isConfigValid() const
{

    // 验证图像保存路径（如果设置了自定义路径）
    if (!m_cfg.imageSavePath.isEmpty()) {
        QFileInfo pathInfo(m_cfg.imageSavePath);
        if (!pathInfo.isDir()) {
            // 如果路径不存在，尝试创建
            QDir dir;
            if (!dir.mkpath(m_cfg.imageSavePath)) {
                return false;
            }
        }
    }

    return true;
}
